using System;
using System.Runtime.InteropServices;
using Microsoft.SharePoint;

namespace IIOS.SP.WebParts.Navigation.Features.IIOS.WebAppNavigator
{
    /// <summary>
    /// This class handles events raised during feature activation, deactivation, installation, uninstallation, and upgrade.
    /// </summary>
    /// <remarks>
    /// The GUID attached to this class may be used during packaging and should not be modified.
    /// </remarks>

    [Guid("6c2e83c6-3f8c-4096-9121-e05cfa21bf17")]
    public class IIOSEventReceiver : SPFeatureReceiver
    {
        // Fields
        private string sListDesc = "Navigation link for IIOS Web Application Navigator web part.";
        private string sListName = "Navigation";

        // Methods
        private void AddLinks(SPSite oSite, SPList oList, int iPos)
        {
            SPWeb rootWeb = null;
            try
            {
                rootWeb = oSite.RootWeb;
                string str = this.CreateLink(oList, rootWeb.Title, "", rootWeb.ServerRelativeUrl, iPos, true);
                int iPosition = 1;
                foreach (SPWeb web2 in rootWeb.Webs)
                {
                    this.CreateLink(oList, web2.Title, string.Format("{0};#{1}", str, rootWeb.Title), web2.ServerRelativeUrl, iPosition, true);
                    iPosition++;
                }
                rootWeb.Update();
            }
            finally
            {
                rootWeb.Dispose();
            }
            
        }

        private string CreateLink(SPList oList, string sTitle, string sParent, string sLocation, int iPosition, bool bDisplay)
        {
            SPListItem item = oList.Items.Add();
            item["Title"] = sTitle;
            if (sParent != "")
            {
                item["ParentLink"] = sParent;
            }
            item["Location"] = sLocation;
            item["Position"] = iPosition;
            item["Display"] = bDisplay;
            item.Update();
            return item["ID"].ToString();
        }

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            if (properties.Feature.Parent is SPSite)
            {
                try
                {
                    using (SPSite site = (SPSite)properties.Feature.Parent)
                    {
                        SPWeb rootWeb = site.RootWeb;
                        Guid lookupListId = rootWeb.Lists.Add(this.sListName.Replace(" ", ""), this.sListDesc, SPListTemplateType.GenericList);
                        rootWeb.Update();
                        SPList oList = rootWeb.Lists[lookupListId];
                        oList.AllowDeletion = false;
                        oList.Hidden = true;
                        oList.Title = this.sListName;
                        oList.ContentTypesEnabled = false;
                        oList.EnableAttachments = false;
                        oList.EnableFolderCreation = false;
                        oList.EnableVersioning = false;
                        oList.NoCrawl = true;
                        oList.OnQuickLaunch = false;
                        oList.Update();
                        oList.Fields.AddLookup("ParentLink", lookupListId, false);
                        oList.Fields.Add("Position", SPFieldType.Integer, true);
                        oList.Fields.Add("Location", SPFieldType.Text, true);
                        oList.Fields.Add("Display", SPFieldType.Boolean, false);
                        this.setFieldProperties(oList.Fields, "Display", "Display", "Makes the link available in the web part", "1");
                        oList.Fields.Add("SecTrim", SPFieldType.Boolean, false);
                        this.setFieldProperties(oList.Fields, "SecTrim", "Security Trim", "Check if user has access before rendering link", "1");
                        SPFieldLookup lookup = (SPFieldLookup)oList.Fields["ParentLink"];
                        lookup.Title = "Parent Link";
                        lookup.LookupField = "Title";
                        lookup.Update();
                        oList.Update();
                        SPView defaultView = oList.DefaultView;
                        defaultView.ViewFields.DeleteAll();
                        defaultView.ViewFields.Add("LinkTitle");
                        defaultView.ViewFields.Add("Parent Link");
                        defaultView.ViewFields.Add("Location");
                        defaultView.ViewFields.Add("Position");
                        defaultView.ViewFields.Add("Display");
                        defaultView.ViewFields.Add("Security Trim");
                        defaultView.ViewFields.Add("Modified By");
                        defaultView.ViewFields.Add("Modified");
                        defaultView.Update();



                        bool bCatchAD = SPSecurity.CatchAccessDeniedException;
                        int iPos = 1;

                        foreach (SPSite site2 in site.WebApplication.Sites)
                        {                            
                            try
                            {
                                SPSecurity.CatchAccessDeniedException = false;
                                this.AddLinks(site2, oList, iPos);
                                iPos++;
                            }
                            catch (UnauthorizedAccessException ex)
                            {
                                continue;
                            }
                            finally
                            {
                                SPSecurity.CatchAccessDeniedException = bCatchAD;
                            }
                        }                        
                    }
                }
                catch (Exception)
                {
                }
            }
        }

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            if (properties.Feature.Parent is SPSite)
            {
                try
                {
                    using (SPWeb web = ((SPSite)properties.Feature.Parent).RootWeb)
                    {
                        SPList list = web.Lists[this.sListName];
                        if (list != null)
                        {
                            list.AllowDeletion = true;
                            list.Update();
                            list.Delete();
                            web.Update();
                        }
                    }
                }
                catch (Exception)
                {
                }
            }
        }

        private void setFieldProperties(SPFieldCollection oFC, string sField, string sTitle, string sDesc, string sDefault)
        {
            new SPField(oFC, sField) { Description = sDesc, Title = sTitle, DefaultValue = sDefault }.Update();
        }
    }
}
